package com.doupi.partner.api.biz;

import com.doupi.partner.api.core.AbstractBiz;
import com.doupi.partner.api.core.ApiRequest;
import com.doupi.partner.api.core.ApiResponse;
import com.doupi.partner.api.core.Security;
import com.doupi.partner.manager.gateway.SmsManager;
import com.doupi.partner.util.AssertUtils;
import com.doupi.partner.util.RedisUtils;
import com.doupi.partner.util.RegexUtils;
import com.doupi.partner.util.RuntimeBusinessException;
import com.doupi.partner.util.constant.UtilConstants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 获取验证码 时效 30分钟
 * 
 * <pre>
 * 		参数：
 * 			mobile[String]：手机号，必填
 * </pre>
 * 
 * @author Super Jens Wang
 * @version 1.0 $id: SmsFacade.java 2016年10月27日 下午2:42:43 Wang Le $
 */
@Security
@Component("sms")
public class SmsFacade extends AbstractBiz {
	private final SmsManager smsManager;

	private final RedisUtils redisUtils;

	private final Producer kaptchaProducer;

	@Autowired
	public SmsFacade(SmsManager smsManager, RedisUtils redisUtils, Producer kaptchaProducer) {
		this.smsManager = smsManager;
		this.redisUtils = redisUtils;
		this.kaptchaProducer = kaptchaProducer;
	}

	@Override
	protected void execute(ApiRequest request, ApiResponse response) {
		String mobile = MapUtils.getString(request.getData(), "mobile");
		AssertUtils.assertNotNull(mobile, "请输入手机号");
		if (!RegexUtils.isMobile(mobile)) {
			throw RuntimeBusinessException.createException("手机号不正确");
		}
		String code = kaptchaProducer.createText();
		redisUtils.setex(UtilConstants.IDENTIFY_CODE_CACHE_KEY_PREFIX + mobile, code, 30 * 60);
		boolean flag = smsManager.sendSMS(mobile, "欢迎使用“逗皮”，验证码为：" + code);
		if (!flag) {
			throw RuntimeBusinessException.createException("发送短信失败");
		}
	}
}
